import { getInfo, getUserDetailById } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { login } from '@/api/user'
import { Message } from 'element-ui'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken('token') || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
      console.log(state.userInfo, 'userinfo')
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async getUserInfo(context) {
      const res = await getInfo()
      console.log(res, '用户信息')
      const info = await getUserDetailById(res.data.userId)
      console.log(info)
      context.commit('setUserInfo', { ...res.data, ...info.data })
      return res.data.roles.menus
    },
    logout(context) {
      context.commit('delToken')
      context.commit('removeUserInfo')
      resetRouter() // 重置路由
    },
    async initToken(context, formData) {
      const res = await login(formData)
      // console.log(res)
      if (res.code !== 10000) return Message.error(res.message)
      Message.success(res.message)
      context.commit('updateToken', res.data)
    }
  }
}
